use strict;
use warnings;
use utf8;
use lib './src';
use Encode qw(encode decode);

use Data::Dumper;
use Mojolicious::Lite;
use Template;
use DBIx::Class;
use Schema::Result::Company;
use Schema::Result::Project;
use Schema::Result::CustomEnum;

use Parse;
use Utils;
use Constants qw(IdentityType_UUID);

use Schema qw();

my $schema = Schema->connect(
    'dbi:SQLite:userdata/code-generate.db',
    '', '',
    {
        sqlite_unicode => 1,
        sqlite_enable_foreign_keys => 1,
        RaiseError => 1,
    }
);

# 自定义的首字符小写过滤器，特殊处理了开头连续的大写字母序列
sub lower_first_caps {
    my ($text) = @_;
    return '' unless defined $text;

    # 检查是否整个字符串都是大写字母
    if ($text =~ /^[A-Z]+$/){
        return lc($text);
    }

    # 否则处理开头连续的大写字母
    $text =~ s/([A-Z]+)/
        my $caps = $1;
        my $length = length($caps);
        if($length >= 2) {
            lc(substr($caps, 0, $length - 1)) . substr($caps, -1);
        } else {
          lc($caps);
        }
    /e;

    return $text;
}

# 配置模板路径和静态文件路径
app->renderer->paths(['src/pages']);
app->static->paths(['src/public']);
app->hook(before_dispatch => sub {
    my $c = shift;
    if($c->req->method eq 'OPTIONS'){

        $c->res->headers->header('Access-Control-Allow-Origin' => '*');
        $c->res->headers->header('Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS');
        $c->res->headers->header('Access-Control-Allow-Headers' => '*');
        $c->res->headers->header('Access-Control-Max-Age' => '86400');

        $c->render(text => '', status => 204);
        return;
    }
});

app->hook(before_render => sub {
    my $c = shift;
    $c->res->headers->header('Access-Control-Allow-Origin' => '*');
    $c->res->headers->header('Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS');
    $c->res->headers->header('Access-Control-Allow-Headers' => '*');
});

my $tt = Template->new({
    FILTERS => {
       lower_first_caps => \&lower_first_caps,
    },
    INCLUDE_PATH => './src/templates',
    INTERPOLATE  => 1,
    ENCODING => 'utf8',
}) || die "$Template::ERROR\n";

app->config( Engine => $tt);

# 工具首页
get '/' => sub {
    my $ctl = shift;
    $ctl->render(template => 'index');
};

# 保存定义模型
post '/save' => sub{
    my $ctl = shift;
    my $filename = $ctl->req->json->{filename};
    my $content = $ctl->req->json->{define};
    my @lines = processContent($content);
    my $filenameReg = qr/package\s+(PPrefix\.)?((\w+)\.)+(\w+)\s*{/;
    if(!defined $filename){
        foreach my $line (@lines){
            if($line =~ /$filenameReg/){
                $filename = $4;
                last;
            }
        }
    }
    SaveFile("./userdata", $filename.'.puml', $content);
    $ctl->render(text => '', status => 200);
};

# 删除定义模型
post '/remove' => sub{
    my $ctl = shift;
    my $filename = $ctl->req->json->{filename};
    RemoveFile("./userdata", $filename.'.puml');
    $ctl->render(text => '', status => 200);
};

# 获取模型列表
get '/list' => sub{
    my $ctl = shift;

    opendir(my $dir_fh, "./userdata") or die "cannot open directory";
    my @files = readdir($dir_fh);
    closedir($dir_fh);

    @files = grep { ! -d "./userdata/$_" && /\.puml$/i } @files;
    @files = map { s/\.puml$//i; $_ } @files;
    @files = sort { lc($a) cmp lc($b) } @files;

    $ctl->render(json => \@files);
};

# 获取模型定义详情
get '/detail' => sub{
    my $ctl = shift;
    my $filename = $ctl->req->query_params->param('filename');
    open(my $fh, '<:encoding(UTF-8)', './userdata/'.$filename.'.puml') or die "cannot open file";
    my $data = do{ local $/; <$fh> };
    close($fh);

    $ctl->render( json => { Data => $data } );
};

# 生成代码
post '/generate' => sub {
    my $ctl = shift;

    my @lines = processContent($ctl->req->json->{define});

    my @aggregateList = GetAggregatesWithoutEnum(@lines);

    my @enums = GetEnums(@lines);

    my @generateCode = ();

    foreach my $aggregate (@aggregateList){
        my $data = [];
        $aggregate->{Enums} = \@enums;
        $aggregate->setEngine(app->config->{Engine});
        $aggregate->generate();
        push @$data, $aggregate->{ClassContent}, $aggregate->{TypeConfigurationContent}, $aggregate->{DDLSql};
        push @generateCode, $data;
    }

    $ctl->render(json => \@generateCode);
};

sub processContent {
    my $content = shift;
    my @lines = split("\n", $content);
    @lines = map { s/\R//g; $_ } @lines;
    return @lines;
}

# -- 组织相关 API

# 创建组织
post '/api/company/create' => sub {
    my $ctl = shift;
    my $comment = $ctl->req->json->{comment};
    my $name = $ctl->req->json->{name};
    my $newCompany = Schema::Result::Company->Create($schema, {Name => $name, Comment => $comment});

    $ctl->render(json => {id => $newCompany->Id})
};

# 获取组织列表
get '/api/company/list' => sub {
    my $ctl = shift;
    my @allCompany = $schema->resultset('Company')->all;

    my @result = ();
    foreach my $company (@allCompany) {
        push @result, {id => $company->Id, name => $company->Name, comment => $company->Comment};
    }
    $ctl->render(json => \@result);
};

# 获取组织所有的项目
get '/api/company/projects' => sub {
    my $ctl = shift;
    my $companyId = $ctl->req->query_params->param('id');

    my $company = $schema->resultset('Company')->find($companyId, {prefetch => 'Projects'});

    if(!defined $company) {
        $ctl->render(json => {error => 'Company Not Found'}, status => 404);
        return;
    }

    my @result = ();
    my @projects = $company->Projects;

    foreach my $project (@projects) {
        push @result, {id => $project->Id,  name => $project->Name, comment => $project->Comment};
    }

    $ctl->render(json => \@result);
};

# 修改组织信息
post '/api/company/modify' => sub {
    my $ctl = shift;
    my $companyId = $ctl->req->json->{id};
    my $name = $ctl->req->json->{name};
    my $comment = $ctl->req->json->{comment};

    my $company = $schema->resultset('Company')->find($companyId);
    if(!defined $company) {
        $ctl->render(json => {error => 'Company Not Found'}, status => 404);
        return;
    }

    $company->Modify($name, $comment);

    $ctl->render(json => {success => Mojo::JSON->true});
};

# 删除组织
post '/api/company/delete' => sub {
    my $ctl = shift;
    my $companyId = $ctl->req->json->{id};

    my $company = $schema->resultset('Company')->find($companyId);
    if(!defined $company) {
        $ctl->render(json => {error => 'Company Not Found'}, status => 404);
        return;
    }

    $company->Delete;

    $ctl->render(json => {success => Mojo::JSON->true});
};


# -- 项目相关 API

# 创建项目
post '/api/project/create' => sub {
    my $ctl = shift;
    my $companyId = $ctl->req->json->{companyId};
    my $name = $ctl->req->json->{name};
    my $comment = $ctl->req->json->{comment};
    my $aggregatePackage = $ctl->req->json->{aggregatePackage};
    my $enumPackage = $ctl->req->json->{enumPackage};
    my $languageType = $ctl->req->json->{languageType};

    my $company = $schema->resultset('Company')->find($companyId);

    if(!defined $company){
        $ctl->render(json => {error => 'Company Not Found'}, status => 404);
        return;
    }

    my $newProject = Schema::Result::Project->Create(
        $schema,
        {
            CompanyId => $companyId,
            Name => $name,
            Comment => $comment,
            AggregatePackage => $aggregatePackage,
            EnumPackage => $enumPackage,
            LanguageType => $languageType
        }
    );

    $ctl->render(json => {id => $newProject->Id});
};

# 获取项目信息
get '/api/project/info' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('id');

    my $project = $schema->resultset('Project')->find($projectId);

    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    $ctl->render(json => {
            id => $project->Id,
            name => $project->Name,
            comment => $project->Comment,
            aggregatePackage => $project->AggregatePackage,
            enumPackage => $project->EnumPackage,
            languageType => $project->LanguageType
        }
    )

};

# 获取项目模型列表
get '/api/project/aggregates' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('id');

    my $project = $schema->resultset('Project')->find($projectId, { prefetch => 'Aggregates' });

    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my @result = ();
    my @aggregates = $project->Aggregates;

    foreach my $aggregate (@aggregates) {
        push @result, {id => $aggregate->Id,  name => $aggregate->Name, comment => $aggregate->Comment};
    }

    $ctl->render(json => \@result);
};

# 获取项目枚举列表
get '/api/project/enums' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('id');

    my $project = $schema->resultset('Project')->find($projectId, { prefetch => 'Enums' });

    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my @result = ();
    my @enums = $project->Enums;

    foreach my $enum (@enums) {
        push @result, {id => $enum->Id,  name => $enum->Name, comment => $enum->Comment};
    }

    $ctl->render(json => \@result);
};

# 获取项目配置列表
get '/api/project/configurations' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('id');

    my $project = $schema->resultset('Project')->find($projectId, { prefetch => 'Configurations' });

    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my @result = ();
    my @Configurations = $project->Configurations;

    foreach my $configuration (@Configurations) {
        push @result, {id => $configuration->Id,  key => $configuration->Key, value => $configuration->Value, comment => $configuration->Comment};
    }

    $ctl->render(json => \@result);
};

# 唯一标识列表
get '/api/project/identities' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('projectId');

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my @identities = $schema->resultset('Identity')->search({ProjectId => $projectId})->all;

    my @result = ();
    foreach my $identity (@identities) {
        push @result, {id => $identity->Id, name => $identity->Name, type => $identity->Type, comment => $identity->Comment};
    }

    $ctl->render(json => \@result);

};

# 修改项目信息
post '/api/project/modify' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{id};
    my $name = $ctl->req->json->{name};
    my $comment = $ctl->req->json->{comment};
    my $aggregatePackage = $ctl->req->json->{aggregatePackage};
    my $enumPackage = $ctl->req->json->{enumPackage};
    my $languageType = $ctl->req->json->{languageType};

    my $project = $schema->resultset('Project')->find($projectId);
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    $project->Modify(
        {
            Name => $name,
            AggregatePackage => $aggregatePackage,
            EnumPackage => $enumPackage,
            LanguageType => $languageType,
            Comment => $comment,
        }
    );

    $ctl->render(json => {success => Mojo::JSON->true});
};

# 删除项目
post '/api/project/delete' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{id};

    my $project = $schema->resultset('Project')->find($projectId);
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    $project->Delete;

    $ctl->render(json => {success => Mojo::JSON->true});
};

# 新建项目配置
post '/api/project/create-configuration' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{id};
    my $key = $ctl->req->json->{key};
    my $value = $ctl->req->json->{value};
    my $comment = $ctl->req->json->{comment};

    my $project = $schema->resultset('Project')->find($projectId);
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $configuration = $project->AddConfiguration($key, $value, $comment);

    $ctl->render(json => {id => $configuration->Id});
};

# 获取配置详情
get '/api/project/configuration-info' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('id');
    my $configurationId = $ctl->req->query_params->param('configurationId');

    my $project = $schema->resultset('Project')->find($projectId, { prefetch => 'Configurations' });
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $configuration = $project->Configurations->find($configurationId);
    if(!defined $configuration){
        $ctl->render(json => {error => 'Configuration Not Found', status => 404});
        return;
    }

    $ctl->render(json => {
        id => $configuration->Id,
        key => $configuration->Key,
        value => $configuration->Value,
        comment => $configuration->Comment,
    });
};

# 修改项目配置
post '/api/project/modify-configuration' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{id};
    my $configurationId = $ctl->req->json->{configurationId};
    my $key = $ctl->req->json->{key};
    my $value = $ctl->req->json->{value};
    my $comment = $ctl->req->json->{comment};

    my $project = $schema->resultset('Project')->find($projectId);
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $result = $project->ModifyConfiguration($configurationId, $key, $value, $comment);

    if($result->{Success}){
        $ctl->render(json => {success => Mojo::JSON->true});
        return;
    }

    $ctl->render(json => {error => $result->{Reason}, 500});
};

# 删除项目配置
post '/api/project/delete-configuration' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{id};
    my $configurationId = $ctl->req->json->{configurationId};

    my $project = $schema->resultset('Project')->find($projectId);
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $result = $project->DeleteConfiguration($configurationId);

    if($result->{Success}){
        $ctl->render(json => {success => Mojo::JSON->true});
        return;
    }

    $ctl->render(json => {error => $result->{Reason}, 500});
};

# -- 枚举相关 API

# 创建自定义枚举
post '/api/custom-enum/create' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{projectId};
    my $name = $ctl->req->json->{name};
    my $comment = $ctl->req->json->{comment};
    my $items = $ctl->req->json->{items};

    my $project = $schema->resultset('Project')->find($projectId);
    if(!defined $project) {
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $customEnum = Schema::Result::CustomEnum->Create(
        $schema,
        {
            ProjectId => $projectId,
            Name => $name,
            Comment => $comment,
            Items => $items,
        }
    );

    $ctl->render(json => {id => $customEnum->Id});

};

# 自定义枚举详情
get '/api/custom-enum/custom-enum-info' => sub {
    my $ctl = shift;
    my $customEnumId = $ctl->req->query_params->param("id");

    my $customEnum = $schema->resultset("CustomEnum")->find($customEnumId, {prefetch => "Items"});
    if(!defined $customEnum){
        $ctl->render(json => {error => 'CustomEnum Not Found'}, status => 404);
        return;
    }

    $ctl->render(json => {
        id => $customEnum->Id,
        projectId => $customEnum->ProjectId,
        name => $customEnum->Name,
        comment => $customEnum->Comment,
        items => [
            map {
                {
                    key => $_->Key,
                    value => $_->Value,
                    comment => $_->Comment,

                }
            } $customEnum->Items->all
        ],
    });

};

# 修改自定义枚举
post '/api/custom-enum/modify' => sub {
    my $ctl = shift;
    my $id = $ctl->req->json->{id};
    my $name = $ctl->req->json->{name};
    my $comment = $ctl->req->json->{comment};
    my $item = $ctl->req->json->{items};

    my $customEnum = $schema->resultset("CustomEnum")->find($id, {prefetch => "Items"});
    if(!defined $customEnum){
        $ctl->render(json => {error => 'CustomEnum Not Found'}, status => 404);
        return;
    }

    my $result = $customEnum->Modify($name, $comment, $item);

    if($result->{Success}){
        $ctl->render(json => {success => Mojo::JSON->true});
        return;
    }

    $ctl->render(json => {error => $result->{Reason}, 500});
};

# 删除自定义枚举
post '/api/custom-enum/delete' => sub {
    my $ctl = shift;
    my $id = $ctl->req->json->{id};

    my $customEnum = $schema->resultset("CustomEnum")->find($id);
    if(!defined $customEnum){
        $ctl->render(json => {error => 'CustomEnum Not Found'}, status => 404);
        return;
    }

    $customEnum->Delete;

    $ctl->render(json => { success => Mojo::JSON->true });

};

# -- 聚合相关 API

# 创建或保存聚合
post '/api/aggregate/save' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{projectId};
    my $content = $ctl->req->json->{content};

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my @lines = processContent($content);

    my $aggregateVo = GetAggregateVo($project->Company->Name, $project->Name, \@lines);
    my $log = $ctl->app->log;
    $log->info("Debug data: " . Dumper($aggregateVo));

    $aggregateVo->{Content} = $aggregateVo->GenerateDefineCode(app->config->{Engine}, 'aggregatePuml.tt2');

    # 校验聚合是否已存在
    my $existsAggregate = $schema->resultset('Aggregate')->find({Name => $aggregateVo->{Name}});
    if(defined $existsAggregate){
        $ctl->render(json => {Error => 'Aggregate Has Exists.', status => 400});
        return;
    }

    eval {
        $schema->storage->txn_begin;
        # 创建模型唯一标识
        my $modelIdentityVoDict = {};
        foreach my $modelVo (@{$aggregateVo->{ModelVos}}){
            my $newIdentity = Schema::Result::Identity->Create($schema,
                {
                    ProjectId => $project->Id,
                    Name => "$modelVo->{Name}Id",
                    Type => IdentityType_UUID, # 默认使用 UUID 后续支持配置
                    Comment => 'Empty Now',
                }
            );
            $modelVo->{IdentityId} = $newIdentity->Id;
        }

        # 创建聚合
        Schema::Result::Aggregate->Create(
            $schema,
            {
                ProjectId => $projectId,
                AggregateVo => $aggregateVo,
            }
        );
        $schema->storage->txn_commit();
    };

    if($@){
        $schema->storage->txn_rollback;
        $ctl->render(json => {error => $@, 500});
        return;
    }

    $ctl->render(json => {success => Mojo::JSON->true});

};

# 聚合详情
get '/api/aggregate/info' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('projectId');
    my $aggregateId = $ctl->req->query_params->param('aggregateId');

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $aggregate = $schema->resultset('Aggregate')->find(
        $aggregateId,
        {
            prefetch => { Models => 'ModelProperties' }
        }
    );

    if( ! defined $aggregate){
        $ctl->render(json => {error => 'Aggregate Not Found'}, status => 404);
        return;
    }

    my $aggregateVo = SchemaVo::AggregateVo->FromAggregate(
        $aggregate,
        $project->Company->Name,
        $project->Name,
        $project->AggregatePackage
    );

    $ctl->render(json => $aggregateVo->ToPlainHash );

};

# 生成代码
get '/api/aggregate/generate-code' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('projectId');
    my $aggregateId = $ctl->req->query_params->param('aggregateId');
    my $templateId = $ctl->req->query_params->param('templateId');

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $aggregate = $schema->resultset('Aggregate')->find(
        $aggregateId,
        {
            prefetch => { Models => 'ModelProperties' }
        }
    );

    if (!defined $aggregate){
        $ctl->render(json => { error => 'Aggregate Not Found' }, status => 404);
        return;
    }

    my $aggregateVo = SchemaVo::AggregateVo->FromAggregate(
        $aggregate,
        $project->Company->Name,
        $project->Name,
        $project->AggregatePackage
    );

    my $template = $schema->resultset('Template')->find($templateId);
    if(!defined $template){
        $ctl->render(json => {error => 'Template Not Found'}, status => 404);
        return;
    }

    my $result = '';
    eval{
        $result = $aggregateVo->GenerateCode(app->config->{Engine}, $template->Content);
    };

    if($@) {
        $ctl->render(json => {error => 'Parse Template Error, Please Check Template'}, status => 500);
        return;
    }

    $ctl->render(json => { generateCode => $result });
};


# -- 唯一标识相关 API

# 创建唯一标识
post '/api/identity/create' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{projectId};
    my $name = $ctl->req->json->{name};
    my $type = $ctl->req->json->{type};
    my $comment = $ctl->req->json->{comment};

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    # 判断唯一标识是否存在
    my $existIdentity = $schema->resultset('Identity')->find({Name => $name, ProjectId => $projectId});
    if(defined $existIdentity){
        $ctl->render(json => {error => 'Identity has being created'}, status => 500);
        return;
    }

    my $newIdentity = Schema::Result::Identity->Create(
        $schema,
        {
            Name => $name,
            ProjectId => $projectId,
            Type => $type,
            Comment => $comment
        }
    );

    $ctl->render(json => {id => $newIdentity->Id});
};

# 唯一标识信息
get '/api/identity/info' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->query_params->param('projectId');
    my $identityName = $ctl->req->query_params->param('name');

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    my $identity = $schema->resultset('Identity')->find({Name => $identityName, ProjectId => $projectId});
    if(!defined $identity){
        $ctl->render(json => {error => 'Identity Not Found'}, status => 404);
        return;
    }

    $ctl->render(json => {
        id => $identity->Id,
        name => $identity->Name,
        type => $identity->Type,
        comment => $identity->Comment,
    });

};

# 修改唯一标识
post '/api/identity/modify' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{projectId};
    my $name = $ctl->req->json->{name};
    my $type = $ctl->req->json->{type};
    my $comment = $ctl->req->json->{comment};

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    # 判断唯一标识是否存在
    my $existIdentity = $schema->resultset('Identity')->find({Name => $name, ProjectId => $projectId});
    if(!defined $existIdentity){
        $ctl->render(json => {error => 'Identity Not Found'}, status => 404);
        return;
    }

    $existIdentity->Modify($type, $comment);

    $ctl->render(json => { success => Mojo::JSON->true });
};

# 删除唯一标识
post '/api/identity/delete' => sub {
    my $ctl = shift;
    my $projectId = $ctl->req->json->{projectId};
    my $identityName = $ctl->req->json->{name};

    my $project = $schema->resultset('Project')->find($projectId);
    if (! defined $project){
        $ctl->render(json => {error => 'Project Not Found'}, status => 404);
        return;
    }

    # 判断唯一标识是否存在
    my $existIdentity = $schema->resultset('Identity')->find({Name => $identityName, ProjectId => $projectId});
    if(!defined $existIdentity){
        $ctl->render(json => {error => 'Identity Not Found'}, status => 404);
        return;
    }

    $existIdentity->Delete;

    $ctl->render(json => { success => Mojo::JSON->true });

};

# -- 模板

# 创建模板
post '/api/template/create' => sub {
    my $ctl = shift;
    my $name = $ctl->req->json->{name};
    my $content = $ctl->req->json->{content};
    my $comment = $ctl->req->json->{comment};

    my $existTemplate = $schema->resultset('Template')->find({Name => $name});
    if(defined $existTemplate){
        $ctl->render(json => {error => 'Template has being created'}, status => 500);
        return;
    }

    my $newTemplate = Schema::Result::Template->Create(
        $schema,
        {
            Name => $name,
            Content => $content,
            Comment => $comment,
        }
    );

    $ctl->render(json => { id => $newTemplate->Id });

};

# 修改模板信息
post '/api/template/modify' => sub {
    my $ctl = shift;
    my $id = $ctl->req->json->{id};
    my $name = $ctl->req->json->{name};
    my $content = $ctl->req->json->{content};
    my $comment = $ctl->req->json->{comment};

    my $template = $schema->resultset('Template')->find($id);

    if(!defined $template){
        $ctl->render(json => { error => 'Template Not Found' }, status => 404);
        return;
    }

    $template->Modify(
        {
            Name => $name,
            Content => $content,
            Comment => $comment,
        }
    );

    $ctl->render(json => {success => Mojo::JSON->true});
};

# 删除模板
post '/api/template/delete' => sub {
    my $ctl = shift;
    my $id = $ctl->req->json->{id};

    my $template = $schema->resultset('Template')->find($id);

    if(!defined $template){
        $ctl->render(json => { error => 'Template Not Found' }, status => 404);
        return;
    }

    $template->Delete;

    $ctl->render(json => {success => Mojo::JSON->true});

};

# 获取模板信息
get '/api/template/info' => sub {
    my $ctl = shift;
    my $templateId = $ctl->req->query_params->param('templateId');

    my $template = $schema->resultset('Template')->find($templateId);
    if (!defined $template){
        $ctl->render(json => {error => 'Template Not Found'}, status => 404);
        return;
    }

    $ctl->render(json => {
        id => $template->Id,
        name => $template->Name,
        content => $template->Content,
        comment => $template->Comment,
    });

};

# 获取模板列表
get '/api/template/list' => sub {
    my $ctl = shift;
    my @allTemplate = $schema->resultset('Template')->all;

    my @result = ();
    foreach my $template (@allTemplate) {
        push @result, {id => $template->Id, name => $template->Name, content => $template->Content, comment => $template->Comment};
    }
    $ctl->render(json => \@result);
};

app->start;

